﻿@using Radzen
@using Radzen.Blazor.Rendering
@using Microsoft.AspNetCore.Components.Forms
@using System.Linq.Expressions
@using System.Globalization
@using Microsoft.JSInterop

@typeparam TValue
@inherits RadzenComponent
@implements IRadzenFormComponent
@if (Visible)
{
    <div @ref="@Element" @attributes="Attributes" class="@GetCssClass()" style="@getStyle()" id="@GetId()">
        @if (!Inline)
        {
            <span class="@($"rz-calendar rz-calendar-w-btn{(Disabled ? " rz-state-disabled" : "")}")" style="width:100%">
                <input @ref="@input" @attributes="InputAttributes" disabled="@Disabled" readonly="@IsReadonly" value="@FormattedValue" tabindex="@(Disabled ? "-1" : $"{TabIndex}")"
                       @onchange="@ParseDate" autocomplete="off" type="text" name="@Name"
                       class="rz-inputtext @InputClass @(IsReadonly ? "rz-readonly" : "")" id="@Name" placeholder="@Placeholder" onclick="@getOpenPopupForInput()"/>
                @if (ShowButton)
                {
	                <button @onmousedown=@OnToggle onclick="@getOpenPopup()" class="@($"rz-datepicker-trigger rz-calendar-button rz-button rz-button-icon-only{(Disabled ? " rz-state-disabled" : "")}")" tabindex="-1" type="button">
		                <span aria-hidden="true" class="@ButtonClasses"></span><span class="rz-button-text"></span>
	                </button>
                }
                @if (AllowClear && HasValue)
                {
                    <i class="rz-dropdown-clear-icon rzi rzi-times" @onclick="@Clear" @onclick:stopPropagation="true"></i>
                }
            </span>
        }

        <Popup id="@PopupID" Lazy=@(PopupRenderMode == PopupRenderMode.OnDemand) @ref=@popup style=@PopupStyle class="@($"{(Inline ? "rz-datepicker-inline " : "")}rz-datepicker")">
                <div class="rz-datepicker-group">
                    @if (!TimeOnly)
                    {
                        <div class="rz-datepicker-header">
                            <a href="javascript:void(0)" class="rz-datepicker-prev" @onclick="@(async () => { if (!Disabled) { try { if(CurrentDate.AddMonths(-1).Year >= YearFrom) {CurrentDate = CurrentDate.AddMonths(-1);}} catch (ArgumentOutOfRangeException) {}} })">
                                <span class="rz-datepicker-prev-icon rzi rzi-chevron-left"></span>
                            </a>
                            <a href="javascript:void(0)" class="rz-datepicker-next" @onclick="@(async () => { if (!Disabled) { try { if(CurrentDate.AddMonths(1).Year <= YearTo) {CurrentDate = CurrentDate.AddMonths(1);}} catch (ArgumentOutOfRangeException) {} } })">
                                <span class="rz-datepicker-next-icon rzi rzi-chevron-right"></span>
                            </a>
                            <div class="rz-datepicker-title">
                                <RadzenDropDown @ref="monthDropDown" Style="height:auto;width:120px;margin-top:5px;text-align:left;" TabIndex="-1"
                                            TValue="int" Value="@CurrentDate.Month" Disabled="@Disabled" Data="@months" TextProperty="Name" ValueProperty="Value"
                                            Change="@((args) => { SetMonth(int.Parse(args.ToString())); })" />
                                <RadzenDropDown @ref="yearDropDown" Style="height:auto;width:80px;margin-top:5px;text-align:left;" TabIndex="-1"
                                            TValue="int" Value="@CurrentDate.Year" Disabled="@Disabled" Data="@years" TextProperty="Name" ValueProperty="Value"
                                            Change="@((args) => { SetYear(int.Parse(args.ToString())); })" />
                            </div>
                        </div>
                        <div class="rz-datepicker-calendar-container">
                            <table class="rz-datepicker-calendar" style="@(Inline ? "" : "width:100%")">
                                <thead>
                                    <tr>
                                        @foreach (var day in ShiftedAbbreviatedDayNames)
                                        {
                                            <th scope="col">
                                                <span>@day</span>
                                            </th>
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    @{
                                        int dayNumber = 0;
                                    }
                                    @for (int i = 0; i < 6; i++)
                                    {
                                        <tr>
                                            @for (int j = 0; j < 7; j++)
                                            {
                                                @if((DateTime.MaxValue - StartDate).TotalDays <= dayNumber)
                                                {
                                                    break;
                                                }
                                                
                                                DateTime date = StartDate.AddDays(dayNumber++);
                                                var dateArgs = DateAttributes(date);

                                                <td @attributes="@(dateArgs.Attributes)" class="@GetDayCssClass(date, dateArgs)" onmouseup=@(PopupRenderMode == PopupRenderMode.OnDemand || Inline || ShowTime || dateArgs.Disabled ? "" : $"Radzen.closePopup('{PopupID}')")
                                                @onclick="@(async () => { if (!Disabled && !dateArgs.Disabled) { await SetDay(date); } })">
                                                    <span class=@GetDayCssClass(date, dateArgs, false)>@date.Day</span>
                                                </td>
                                            }
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                        @if (FooterTemplate != null)
                        {
                            <div class="rz-datepicker-footer">
                                 @FooterTemplate
                            </div>
                        }
                    }
                </div>
                @if (ShowTime)
                {
                <div class="rz-timepicker" @onmousedown:stopPropagation>
                        <RadzenNumeric TValue="int" Disabled="@Disabled" Value="@(HourFormat == "12" ? ((CurrentDate.Hour + 11) % 12) + 1 : CurrentDate.Hour)" 
                           Min="@(HourFormat == "12" ? 1 : -1)" Max="@(HourFormat == "12" ? 12 : 24)" TValue="double" Step="@HoursStep"
                           Change="@UpdateHour" class="rz-hour-picker" @oninput=@OnUpdateHourInput Format="@(PadHours ? "00" : "")" />
                        <div class="rz-separator">
                            <span>:</span>
                        </div>
                        <RadzenNumeric TValue="int" Disabled="@Disabled" Value="CurrentDate.Minute" TValue="double" Step="@MinutesStep" Min="0" Max="59"
                           Change="@UpdateMinutes" class="rz-minute-picker" @oninput=@OnUpdateHourMinutes Format="@(PadMinutes ? "00" : "")" />
                        @if (ShowSeconds)
                        {
                            <div class="rz-separator">
                                <span>:</span>
                            </div>
                            <RadzenNumeric TValue="int" Disabled="@Disabled" Value="CurrentDate.Second" TValue="double" Step="@SecondsStep" Min="0" Max="59"
                               Change="@UpdateSeconds" class="rz-second-picker" @oninput=@OnUpdateHourSeconds Format="@(PadSeconds ? "00" : "")"/>
                        }
                        @if (HourFormat == "12")
                        {
                            <div class="rz-ampm-picker">
                                <a href="javascript:void(0)" @onclick="@ToggleAmPm">
                                    <span class="rzi rzi-chevron-up"></span>
                                </a>
                                <span>@CurrentDate.ToString("tt")</span>
                                <a href="javascript:void(0)" @onclick="@ToggleAmPm">
                                    <span class="rzi rzi-chevron-down"></span>
                                </a>
                            </div>
                        }
                        @if (ShowTimeOkButton)
                        {
                            <button type="button" class="rz-button rz-button-md rz-secondary"
                        @onclick="@OkClick"
                        onmouseup="@($"Radzen.closePopup('{PopupID}')")">
                                <span class="rz-button-text">Ok</span>
                            </button>
                        }
                    </div>
                }
        </Popup>
        
    </div>
}
